﻿#include "InputBox.h"

bool InputBox::init(const std::string &textHint, int limit, int fntSize)
{
	if (!Layer::init())
	{
		return false;
	}

	_limit = limit;
	_textFiel = TextFieldTTF::textFieldWithPlaceHolder(textHint, cfg::getFntName(), fntSize);
	_textFiel->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
	_textFiel->setPosition(0, fntSize / 2);
	this->addChild(_textFiel);

	_textFiel->setDelegate(this);

	this->setContentSize(Size(fntSize * limit / 2, fntSize));
	this->setIgnoreAnchorPointForPosition(false);
	this->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);

	auto touchListener = EventListenerTouchOneByOne::create();
	touchListener->onTouchBegan = CC_CALLBACK_2(InputBox::onTouchBegan, this);
//	touchListener->onTouchMoved = Q_BIND2(InputBox::onTouchMoved, this);
	touchListener->onTouchEnded = CC_CALLBACK_2(InputBox::onTouchEnded, this);
	touchListener->onTouchCancelled = touchListener->onTouchEnded;
	_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
	return true;
}


void InputBox::setPositionForIME(Vec2 vecBegin, Vec2 vecInput)
{
	_isSetPositionForIME = true;
	_vecBegin = vecBegin;
	_vecInput = vecInput;
}




void InputBox::keyboardWillShow(IMEKeyboardNotificationInfo& info)
{
	if (_isSetPositionForIME)
	{
		this->setPosition(_vecBegin);
	}

}



void InputBox::keyboardDidHide(IMEKeyboardNotificationInfo& info)
{
	if (_isSetPositionForIME)
	{
		this->setPosition(_vecInput);
	}
}



bool InputBox::onTextFieldInsertText(TextFieldTTF * sender, const char * text, size_t nLen)
{
	return true;
//	return cpp::get(_textFiel->getString()) + cpp::getInputLength(string(text, nLen)) > _limit;
}


void InputBox::onTouchEnded(Touch *touch, Event *unused_event)
{
	Vec2 v = touch->getLocation();
	if (v.distance(touch->getStartLocation()) > 5)
	{
		return;
	}

	Vec2 vChild = this->convertToNodeSpace(v);
	v = this->getParent()->convertToNodeSpace(v);
	bool isClick = _textFiel->getBoundingBox().containsPoint(vChild);
	isClick = isClick || this->getBoundingBox().containsPoint(v);
	if (isClick)
	{
		_textFiel->attachWithIME();
	}
	else
	{
		_textFiel->detachWithIME();
	}
}
